package com.fjnu.dao.impl;

import com.fjnu.dao.TagDao;
import com.fjnu.entity.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class TagDaoImpl implements TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Tag tag) {
        if(tag.getName() == null)
            return 0;
        String sql = "INSERT INTO tb_tag (name, create_time, update_time) VALUES (?, NOW(), NOW())";
        return jdbcTemplate.update(sql, tag.getName());
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer tagId) {
        if(articleId == null || tagId == null)
            return 0;
        String sql = "INSERT INTO tb_article_tag (article_id, tag_id) VALUES (?, ?)";
        try {
            return jdbcTemplate.update(sql, articleId, tagId);
        } catch (DataIntegrityViolationException e) {
            // 捕获外键约束违反异常，返回0表示插入失败
            return 0;
        }
    }
    
    @Override
    public List<Tag> selectAll() {
        String sql = "SELECT * FROM tb_tag";
        return jdbcTemplate.query(sql, new TagRowMapper());
    }
    
    @Override
    public int delete(Integer tagId) {
        String sql = "DELETE FROM tb_tag WHERE id = ?";
        return jdbcTemplate.update(sql, tagId);
    }
    
    private static class TagRowMapper implements RowMapper<Tag> {
        @Override
        public Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
            Tag tag = new Tag();
            tag.setId(rs.getInt("id"));
            tag.setName(rs.getString("name"));
            tag.setCreateTime(rs.getTimestamp("create_time"));
            tag.setUpdateTime(rs.getTimestamp("update_time"));
            return tag;
        }
    }
}